/*
 * @Author: zwc 6537397+uni-yunApp@user.noreply.gitee.com
 * @Date: 2021-02-22 18:19:38
 * @LastEditors: zwc 6537397+uni-yunApp@user.noreply.gitee.com
 * @LastEditTime: 2023-04-13 17:19:59
 * @FilePath: \ant-design-vue-admin-master\src\configs\permission.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { message } from 'ant-design-vue'
import NProgress from 'nprogress'
import router, { resetRouter } from '@/router'
import { constantRouterMap, asyncRouterMap } from '@/router/router.config'
import store from '@/store'
import { filterAsyncRoutes, setPageTitle } from '@/utils'
import { toLogin } from '@/utils/common'

import 'nprogress/nprogress.css'

const WHITE_LIST = ['/noPermission', '/404', '/505'] // 重定向白名单

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  document.title = setPageTitle(to.meta.title)
  if (WHITE_LIST.includes(to.path)) {
    next()
  } else {
    // 判断是否有登录信息
    const { userInfo } = store.getters
    console.log('store.getters', userInfo)
    if (JSON.stringify(userInfo) === '{}') {
      console.log('进来了')
      // 请求用户详情接口
      store
        .dispatch('GetUserInfo')
        .then(res => {
          // console.log('用户信息',res)
          if (res) {
            // 获取到用户信息
            store
              .dispatch('GenerateRoutes', res)
              .then(res => {
                console.log('菜单信息---', res)
                // 获取菜单信息
                if (res) {
                  next(to.path)
                } else {
                  next({
                    path: '/noPermission',
                    query: {
                      msg: res && res.errorMessage,
                      code: res && res.errorCode,
                      loginUrl: res && res.redirectURL
                    }
                  }) // 没有获取菜单信息就直接跳转到错误页面
                }
              })
              .catch(err => {
                next({ name: 'noPermission', query: { msg: `获取菜单出错了,因为${err}` } }) // 没有获取菜单信息就直接跳转到错误页面
              })
          } else {
            // 没有获取用户信息就没有权限
            next({ name: 'noPermission', query: { msg: '获取用户信息失败' } })
            NProgress.done()
          }
        })
        .catch((error) => {
          console.log('error', error)
          setTimeout(() => {
            toLogin()
          }, 2000)
        })
    } else {
      next()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
